<?php

namespace app\stores\controller\miniapp\buy;

use app\BaseController;
use app\beautiful\logic\LogsLogic;
use app\stores\logic\MemberWalletLogic;
use app\beautiful\logic\printer\PrinterLogic;
use app\beautiful\model\member\MemberCouponModel;
use app\beautiful\model\setting\SettingBalanceModel;
use app\beautiful\model\setting\SettingBuyModel;
use app\beautiful\model\setting\SettingIntegralModel;
use app\common\logic\DataLogic;
use app\common\model\ShopDetailModel;
use app\common\model\ShopModel;
use app\stores\model\member\MemberLevelModel;
use app\stores\model\order\BuyOrderModel;
use think\facade\Db;


class Buy extends BaseController{
    /*买单数据初始化*/
    public function init(){
        $lng =  $this->request->param('lng/f',0);
        $lat =  $this->request->param('lat/f',0);
        $buySetting = SettingBuyModel::where([['shop_id','=', $this->request->shopId]])->find();
        if(empty($buySetting) || $buySetting->is_open == 0){
            return $this->error('小程序未开启在线买单功能');
        }
        $return = [
            'is_open' => $buySetting->is_open,
            'is_use_coupon' => $buySetting->is_use_coupon,
            'is_integral_deduction_balance' => $buySetting->is_integral_deduction_balance,
            'is_vip_discount'  => $buySetting->is_vip_discount,
            'coupons'   => [], //可以选择的用户优惠券
            'integral_deduction_balance_limit_rate' => 0,//积分使用的上限比例
            'integral_exchange_balance' => 0, //积分抵扣余额的汇率 100积分等于多少元
            'vip_discount' => 10, //会员折扣
        ];
        if($buySetting->is_integral_deduction_balance == 1){ //允许使用积分抵扣的情况下
            $SettingBalance = SettingBalanceModel::where([['shop_id','=', $this->request->shopId]])->find();
            if(null === $SettingBalance){
                $return['is_integral_deduction_balance'] = 0;
                $return['integral_deduction_balance_limit_rate'] = 0;
            }else{
                $return['integral_deduction_balance_limit_rate'] = $SettingBalance->integral_deduction_balance_limit_rate; //积分抵扣的比率 百分比
            }
            $integralSetting = SettingIntegralModel::where([['shop_id','=', $this->request->shopId]])->find();
            if($integralSetting === null){ //如果是空 代表不使用积分抵扣余额
                $return['is_integral_deduction_balance'] = 0;
                $return['integral_deduction_balance_limit_rate'] = 0;
                $return['integral_exchange_balance'] = 0;
            }else{
                $return['integral_exchange_balance'] = $integralSetting->integral_exchange_balance;//汇率
            }
        }
        if($buySetting->is_vip_discount == 1){
            $model = new MemberLevelModel();
            $where[]=['ml.vip_start_time','<=',date('Y-m-d H:i:s')];
            $where[]=['ml.vip_end_time','>=',date('Y-m-d H:i:s')];
            $where[]=['ml.member_id','=',$this->request->memberId];
            $where[]=['ml.shop_id','=',$this->request->shopId];

            $level = $model->getLevel($where,'ml.*,l.discount_force');

            $return['vip_discount'] =(null === $level)?0:$level->discount_force;
        }
        if($buySetting->is_use_coupon == 1){
            $today = date('Y-m-d',time());
            $coupons = MemberCouponModel::where([
                ['shop_id','=', $this->request->shopId],
                ['member_id','=', $this->request->memberId],
                ['valid_bg_time','<=',$today],
                ['valid_end_time','>=',$today],
                ['status','=',0],
            ])->limit(0,50)->select()->toArray(); //最多下发50条
            $return['coupons'] = $coupons;
        }

        //门店信息
        $shop = ShopModel::with(['detail'=>function($query){
            $query->json(['business_time'],true)
                ->field('shop_id,business_time,logo,per_money,tel,address,lng,lat,t_lat,t_lng');
        }])->where(['shop_id'=>$this->request->shopId])
            ->field('shop_id,name')
            ->find();

        $distance = get_distance($lat,$lng,$shop->detail->t_lat,$shop->detail->t_lng);
        $is_open = 0;
        $business_time = $shop->detail->business_time;
        if($business_time){
            //是否营业中
            for ($i=0;$i<count($business_time);$i++){
                $start = strtotime(date('Y-m-d').' '.$business_time[$i]['start'].':00');
                $end = strtotime(date('Y-m-d').' '.$business_time[$i]['end'].':00');
                $now = time();
                if($now>=$start && $now<=$end){
                    $is_open = 1;
                }
            }
        }
        $shop->detail->lng = $shop->detail->t_lng;
        $shop->detail->lat = $shop->detail->t_lat;
        $shop_info = $shop->detail;
        $shop_info['distance'] = $distance;
        $shop_info['is_open'] = $is_open;
        $shop_info['business_time'] = $business_time;
        $return['shop'] = $shop_info;
        return $this->success([
            'buyInfo' => $return
        ]);
    }
    /*买单记录*/
    public function getMemberBuyLogs()

    {
        $where = [
            ['member_id','=',$this->request->memberId],
            ['is_paid','=',1]
        ];
        //存在的门店
        $shop_ids = ShopModel::where(['open_status'=>1])->column('shop_id');
        $where[] = ['shop_id','In',$shop_ids];
        
        $order = ['add_time'=>'desc'];

        $model = BuyOrderModel::with(['member_coupon','refundLogs','shop'=>function($query){

            $query->with(['detail']);

        }]);

        $field = "balance,vip_balance,coupon_money,integral_balance,is_paid,pay_time,add_time";

        $append = ['add_time_format','pay_time_format','pay_type_mean','price','discount_money'];

        $return = DataLogic::getDataList($model,$where,$order,$field,$this->request->limit,$this->request->page,$append);

        $list = $return['list'];

        foreach ($list as $k=>$v){
            $list[$k]['shop_name'] = $v['shop']['name'];
            $list[$k]['shop_logo'] = $v['shop']['detail']['logo'];
            $list[$k]['member_coupon_name'] = $v['member_coupon']?$v['member_coupon']['name']:null;
            unset($list[$k]['member_coupon']);
            unset($list[$k]['shop']);
            //是否部分退款
            $list[$k]['is_bf_refund'] = ($v['refund_money']>0 && $v['status']!=3)?1:0;
        }

        $return['list'] = $list;

        return $this->success($return);

    }

    /* 买单钱包支付*/
    public function buyPlatformMoneyPayment(){
        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if(null === $order = \app\beautiful\model\order\BuyOrderModel::find($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('请选择要支付的订单');
        }
        Db::startTrans();
        try{
            //待付款选择混合支付修改订单
            if($mix_pay_type){
                //判断支付方式
                $params['mix_pay_type'] = $mix_pay_type;
                $return = checkPayWay($params,$order->need_pay,$this->request->memberId,$this->request->shopId);

                if($return['error']){
                    return $this->error($return['error']);
                }else{
                    $mix_pay_money = $return['mix_pay_money'];
                    $mix_pay_type=(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null;
                    $platform_money = isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0;
                    $money = isset($mix_pay_money['money'])?$mix_pay_money['money']:0;
                    $weixin = isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0;
                }
            }else{
                $mix_pay_type = null;
                $platform_money = $money = $weixin = 0;
            }
            $order->mix_pay_type = $mix_pay_type;
            $order->platform_money = $platform_money;
            $order->money = $money;
            $order->weixin = $weixin;
            $order->save();
            $order = \app\beautiful\model\order\BuyOrderModel::find($order_id);

            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 5, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->integral, 6);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->balance * 100 - $order->vip_balance * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }

            $order->is_paid = 1;
            $order->pay_time = time();
            $order->pay_type = 'platform_money';
            $order->edit_time = date('Y-m-d H:i:s');
            $order->status = 1;
            if(empty($mix_pay_type)) $order->platform_money = $order->pay_money;
            $order->save();

            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',1);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else {
                $StoresMemberWalletLogic = new \app\stores\logic\MemberWalletLogic($this->request->shopId, $this->request->memberId);
                $res = $StoresMemberWalletLogic->usePlatformMoney($needPay, $order->buy_order_id,0,0,2);
                if($res == false){
                    Db::rollback();
                    return $this->error($StoresMemberWalletLogic->getError());
                }
            }

            //股东分红
            order_bonus($order_id,1);

            //语音播报
            $detail = ShopDetailModel::where(['shop_id'=>$this->request->shopId])->find();
            $voice['msg'] = '优优盟钱包收款'.$needPay.'元';
            $voice['sbx_id'] = $detail->sbx_id;
            sendvoice($voice);
            //打印机
            $printer_logic =new PrinterLogic($this->request->shopId);
            $printer_logic->print('buy',$order->buy_order_id);
            Db::commit();
            return $this->success('钱包支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

    /*买单余额支付*/
    public function buyMoneyPayment(){
        $order_id = $this->request->param('order_id/d');
        $mix_pay_type = $this->request->param('mix_pay_type');
        if(empty($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if(null === $order = \app\beautiful\model\order\BuyOrderModel::find($order_id)){
            return $this->error('请选择要支付的订单');
        }
        if($order->shop_id != $this->request->shopId || $order->member_id != $this->request->memberId){
            return $this->error('请选择要支付的订单');
        }
        Db::startTrans();
        try{
            //待付款选择混合支付修改订单
            if($mix_pay_type){
                //判断支付方式
                $params['mix_pay_type'] = $mix_pay_type;
                $return = checkPayWay($params,$order->pay_money,$this->request->memberId,$this->request->shopId);

                if($return['error']){
                    return $this->error($return['error']);
                }else{
                    $mix_pay_money = $return['mix_pay_money'];
                    $mix_pay_type=(isset($mix_pay_money) && $mix_pay_money)?implode(',',array_keys($mix_pay_money)):null;
                    $platform_money = isset($mix_pay_money['platform_money'])?$mix_pay_money['platform_money']:0;
                    $money = isset($mix_pay_money['money'])?$mix_pay_money['money']:0;
                    $weixin = isset($mix_pay_money['weixin'])?$mix_pay_money['weixin']:0;
                }
            }else{
                $mix_pay_type = null;
                $platform_money = $money = $weixin = 0;
            }
            $order->mix_pay_type = $mix_pay_type;
            $order->platform_money = $platform_money;
            $order->money = $money;
            $order->weixin = $weixin;
            $order->save();
            $order = \app\beautiful\model\order\BuyOrderModel::find($order_id);

            if(!empty($order->member_coupon_id)){
                if(null === $myCoupon = MemberCouponModel::find($order->member_coupon_id)){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                if($myCoupon->status == 1){
                    Db::rollback();
                    return $this->error('优惠券不存在');
                }
                $myCoupon->status = 1;
                $myCoupon->save();
                LogsLogic::coupon($this->request->shopId, $this->request->memberId, -1, 5, $order->member_coupon_id, '', 0);
            }
            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $this->request->memberId);
            if(!empty($order->integral)){ //使用积分
                $res = $MemberWalletLogic->useIntegral($order->integral, 6);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }
            $needPay = round(($order->balance * 100 - $order->vip_balance * 100 - $order->coupon_money * 100 - $order->integral_balance * 100)/100,2);
            if($needPay <= 0){
                Db::rollback();
                $this->error('支付金额不正确');
            }

            if(!empty($mix_pay_type)){
                $return = mix_pay_money($order,'',1);
                if($return['error']){
                    Db::rollback();
                    return $this->error($return['error']);
                }
            }else {
                $res = $MemberWalletLogic->useBalance($needPay, $order->balance, 5);
                if($res == false){
                    Db::rollback();
                    return $this->error($MemberWalletLogic->getError());
                }
            }

            $order->is_paid = 1;
            $order->pay_time = time();
            $order->pay_type = 'money';
            $order->edit_time = date('Y-m-d H:i:s');
            $order->status = 1;
            if(empty($mix_pay_type)) $order->money = $order->pay_money;
            $order->save();
            //股东分红
            order_bonus($order_id,1);
            //语音播报
            $detail = ShopDetailModel::where(['shop_id'=>$this->request->shopId])->find();
            $voice['msg'] = '优优盟储值卡收款'.$needPay.'元';;
            $voice['sbx_id'] = $detail->sbx_id;
            sendvoice($voice);
            //打印机
            $printer_logic =new PrinterLogic($this->request->shopId);
            $printer_logic->print('buy',$order->buy_order_id);
            Db::commit();
            return $this->success('余额支付成功');
        }catch(\Exception $e){
            Db::rollback();
            return $this->error($e->getMessage());
        }
    }

}

